﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

public static class I18N
{
    static Dictionary<string, string> mContentDict;


    public static void Init(Dictionary<string, string> newContentDict)
    {
        mContentDict = newContentDict;
    }

    /// <summary>
    /// Translation
    /// </summary>
    public static string _(string key)
    {
        return mContentDict[key];
    }

    public static void SerializeToFile(string savedFile)
    {
        var bytes = SerializeToBytes();

        File.WriteAllBytes(savedFile, bytes);
    }

    public static void DeserializeFromFile(string savedFile)
    {
        var bytes = File.ReadAllBytes(savedFile);

        DeSerializeFromBytes(bytes);
    }

    public static string SerializeToString()
    {
        var bytes = SerializeObject(mContentDict);
        return Encoding.UTF8.GetString(bytes);
    }

    public static void DeSerializationFromString(string content)
    {
        var bytes = Encoding.UTF8.GetBytes(content);
        DeSerializeFromBytes(bytes);
    }

    public static byte[] SerializeToBytes()
    {
        return SerializeObject(mContentDict);
    }

    public static void DeSerializeFromBytes(byte[] byteArr)
    {
        mContentDict = DeserializeObject(byteArr) as Dictionary<string, string>;
    }

    static byte[] SerializeObject(object obj)
    {
        if (obj == null) return null;

        var memoryStream = new MemoryStream();
        var formatter = new BinaryFormatter();
        formatter.Serialize(memoryStream, obj);
        memoryStream.Position = 0;

        var read = new byte[memoryStream.Length];
        memoryStream.Read(read, 0, read.Length);
        memoryStream.Close();
        return read;
    }

    static object DeserializeObject(byte[] byteArr)
    {
        object newObj = null;

        if (byteArr == null) return newObj;

        var memoryStream = new System.IO.MemoryStream(byteArr);
        memoryStream.Position = 0;
        var formatter = new BinaryFormatter();
        newObj = formatter.Deserialize(memoryStream);
        memoryStream.Close();

        return newObj;
    }
}
